<template>
  <el-dialog
    :title="textMap[dialogStatus]"
    :visible.sync="dialogFormVisible"
    @close="closeDlg()"
    width="800px"
    destroy-on-close
    >
    <div>
      <el-row :gutter="20">
        <div class="wapperSon">
          <el-autocomplete
            class="inline-input"
            style="max-width:120px;font-size:12px;"
            v-model="queryConditions.orderNo"
            :fetch-suggestions="querySearch"
            placeholder="订单编号"
            @select="handleSelect"
            @input="handleInput"
          ></el-autocomplete>
          <el-input
            v-model="queryConditions.productNo"
            placeholder="产品编号"
            style="max-width:120px;font-size:12px;"
          ></el-input>
          <span>交期: </span>
          <el-date-picker
            style="max-width:240px;font-size:12px;"
            v-model="deliveryDates"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleDateSelectChange"
          >
          </el-date-picker>
       
          <el-button-group style="float: left">
            <el-button
              type="primary"
              icon="el-icon-search"
              class="el-button--medium"
              @click="fetchData"
              >查询</el-button
            >
            <el-button
              type="primary"
              style="float: "
              icon="el-icon-plus"
              @click="addOrders"
            >
              添加
            </el-button>
          </el-button-group>
        </div>
      </el-row>
      <el-row :gutter="20">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span>订单列表</span>
          </div>
          <el-row type="flex" justify="start">
            <el-table
              v-loading="listLoading"
              :data="list"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @row-click="rowClick"
              @selection-change="handleSelectionChange"
            >
              >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column
                align="center"
                label="订单编号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.orderNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="产品编号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.productNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="产品名称"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.productName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="产品型号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.model }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="客户需求量"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.qty }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="交货时间"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.dRefDeliveryDate }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="生产线"
                width="95"
                style="display:none;"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.produceLineNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="生产线"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.produceLineName }}
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="listQuery.page"
              :limit.sync="listQuery.limit"
              :page-sizes="listQuery.pageSizes"
              @pagination="fetchData"
            />
          </el-row>
        </el-card>
      </el-row>
    </div>
  </el-dialog>
</template>

<script>
import Pagination from "@/components/Pagination"; 
import {
  getAll,
  getList,
  create,
  update,
  deleteBatch,
  getOrderProductDtlVo
} from "@/api/sale/saleOrderProductNoDtl";

import {
  getAll as queryAllOrders,
  create as createProducePlan
} from "@/api/produce/schedulePlan/ProduceOrderProductPlanApi";
import moment, { duration } from "moment";


export default {
  name: "orderselectdlg",
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  props: {
    dialogVisible: false
  },
  watch: {
    dialogVisible: function(newValue, oldValue) {
      if (newValue != null) {
        this.dialogFormVisible = newValue;
        this.fetchData()
      }
    },
    deep: true
  },
  data() {
    return {
      data2: [],
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentSaleOrderMstTypeId: 0,
      dialogFormVisible: false,
      dialogStatus: "create",
      textMap: {
        update: "添加订单",
        create: "添加订单"
      },
      //表格變量
      lstSelected: [],
      queryConditions: {
        orderNo: "",
        productNo: "",
        deliveryStartDate: "", // moment(new Date(1900, 5, 27, 15, 44, 11)).format("YYYY-MM-DD"),
        deliveryEndDate: "" //moment(new Date()).format("YYYY-MM-DD"),
      },
      lstOrders: [],
      deliveryDates: [],
      temp: {
        id: undefined,
        orderNo: "",
        productNo: "",
        productName: "",
        produceLineId: 0,
        produceLineNo: "",
        produceLineName: "",
        batch: "",
        totalAmount: "",
        producedAmount: "",
        planAmount: "",
        deliveryDate: "",
        planProduceStartDate: "",
        planProduceEndDate: "",
        duration: "",
        latestProduceStartDate: "",
        scheduleSate: "",
        freeFloat: "",
        priority: 0
      }
    };
  },
  computed: {},
  created() {
    this.fetchData();
    this.getAllOrders();
  },
  methods: {
    resetTemp() {
      this.temp = {
        id: undefined,
        orderNo: "",
        productNo: "",
        productName: "",
        produceLineId: 0,
        produceLineNo: "",
        produceLineName: "",
        batch: "",
        totalAmount: "",
        producedAmount: "",
        planAmount: "",
        deliveryDate: "",
        planProduceStartDate: "",
        planProduceEndDate: "",
        duration: "",
        latestProduceStartDate: "",
        scheduleSate: "",
        freeFloat: "",
        priority: 0
      };
    },
    handleSelectionChange(val) {
      this.lstSelected = val;
      const type = this.list.find(v => v.therbligsNo === val.therbligsNo);
      if (type != null) {
        this.currentSaleOrderMstTypeId = type.id;
      }
    },
    fetchData() {
      let params = {
        page: this.listQuery.page,
        size: this.listQuery.limit
      };
      params = Object.assign(params, this.queryConditions);
      return getOrderProductDtlVo(params).then(response => {
        this.list = response.data.records;
        console.log(this.list);
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    rowClick(row, column, event) {
      this.currentSaleOrderMstTypeId = row.id;
      this.fetchData();
    },
    handleDateSelectChange(val) {
      this.queryConditions.deliveryStartDate = moment(val[0]).format(
        "YYYY-MM-DD"
      );
      this.queryConditions.deliveryEndDate = moment(val[1]).format(
        "YYYY-MM-DD"
      );
    },
    querySearch(queryString, cb) {
      let orders = this.lstOrders;
      let results = queryString
        ? this.lstOrders.filter(this.createFilter(queryString))
        : this.lstOrders;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return p => {
        return p.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
      };
    },
    handleSelect(val) {
      this.queryConditions.orderNo = val.value;
    },
    handleInput(val) {
      this.queryConditions.orderNo = val;
    },
    getAllOrders() {
      queryAllOrders().then(response => {
        let result = response.data;
        if (result != null && result.length > 0) {
          result.map(v => {
            this.lstOrders.push({ value: v.orderno });
          });
        }
      });
    },
    closeDlg() {
      this.dialogFormVisible = false;
      this.$emit("hideDlg", this.dialogFormVisible);
    },
    addOrders() {
      if (this.lstSelected == null || this.lstSelected.length == 0) {
        this.$message.error("请先选择一条订单详情");
        return;
      }
      let hasErr = false;
      for (let i = 0; i < this.lstSelected.length; i++) {
        //构造一条排产计划
        this.resetTemp();
        this.temp.id = 0;
        this.temp.orderNo = this.lstSelected[i].orderNo;
        this.temp.productNo = this.lstSelected[i].productNo;
        this.temp.productName = this.lstSelected[i].productName;
        this.temp.produceLineName = this.lstSelected[i].produceLineName;
        this.temp.produceLineNo = this.lstSelected[i].produceLineNo;
        this.temp.produceLineId = this.lstSelected[i].produceLineId;
        this.temp.batch = "";
        this.temp.planAmount = this.lstSelected[i].qty;
        this.temp.producedAmount = 0;
        this.temp.deliveryDate = this.lstSelected[i].dRefDeliveryDate;
        this.temp.totalAmount = this.lstSelected[i].qty;
        this.temp.planProduceStartDate = null;
        this.temp.planProduceEndDate = "";
        this.temp.duration = "";
        this.temp.scheduleSate = 0; //未排产
        this.temp.freeFloat = 0;
        this.temp.priority - 999;
        //保存
        createProducePlan(this.temp)
          .then(() => {
              this.$emit("refreshTbl");
          })
          .catch(err => {
            hasErr = true;
            console.log(err);
          });
      }
      if (!hasErr) {
        this.$notify({
          title: "Success",
          message: "添加成功！",
          type: "success",
          duration: 2000
        });
        this.dialogFormVisible = false;
      }
    }
  }
};
</script>
<style scoped>
.item1 {
  margin-top: 20px;
}
.wapperSon {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
.app-container {
  padding: 0;
}
</style>
